package com.qf;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class ShiroDemo {

    public static void main(String[] args) {
        //前端传参： 账号：zhangsan 密码：123456
        String username = "zhangsan";
        String password = "123456";


        //权限管理器
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        //加载 shiro的配置信息
        IniRealm realm = new IniRealm("classpath:shiro.ini");
        //把用户和权限信息 设置给 权限管理器（shiro 核心管理器）
        securityManager.setRealm(realm);

        SecurityUtils.setSecurityManager(securityManager);

        //获取 subject(对外（登录，权限， 退出， 等等）的api )
        Subject subject = SecurityUtils.getSubject();


        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            //登录操作
            subject.login(token);

            System.out.println(subject.isAuthenticated() ? "已认证" : "未认证");
            System.out.println(subject.hasRole("admin") ? "有管理员角色" : "没有管理员角色");
            System.out.println(subject.isPermitted("sys:user:add") ? "有用户所有操作权限" : "没有用户所有操作");

        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("未知的用户");
        }


    }
}
